package com.gsit.ocrbatch.controller;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.gsit.ocrbatch.domain.Record;
import com.gsit.ocrbatch.services.OcrFileReader;
import com.gsit.ocrbatch.services.OcrFileWriter;
import com.gsit.ocrbatch.services.RecordService;


@Repository
public class OcrProcesser {
	
	private List<Record> records;
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Autowired
	private RecordService recordService;
	
	@Autowired
	private OcrFileReader fileReader;
	
	@Autowired
	private OcrFileWriter fileWriter;
	
	@Transactional
	public void execute()throws Exception{
		read();
		for (Record record : records) {
			process(record);
		}
		write();
	}
	
	
	private void read()throws IOException{
		
		records = fileReader.findAllFile();
	}
	
	
	private void write()throws IOException{
		fileWriter.write(records);
	}
	
	
	private void process(Record record) throws Exception {
		recordService.save(record);
		entityManager.clear();
		/*Record other = (Record) entityManager.find(Record.class, record.getId());
		assertEquals(new Long(1), other.getId());*/
	}
	
	public void show(){
		for (Record record : records) {
			System.out.println(" >>>>>>>>"+record.getName());
		}
	}
	

}
